package servlet.info_register;

import utility.User;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import javax.servlet.http.HttpSession;
import java.sql.*;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet{
    private static final long serialVersionUID=1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/photo_project?characterEncoding=utf-8", "root", "mrt286933605");
            String uname = req.getParameter("userName");
            String upwd = req.getParameter("userPwd");
            ps = con.prepareStatement("select * from user where user_name = ?");
            ps.setString(1, uname);
            rs = ps.executeQuery();
            if (rs.next()) {
                resp.sendRedirect("register.jsp");
            } else {
                ps = con.prepareStatement("insert into user(user_name,user_password) values( ? , ? )");
                ps.setString(1, uname);
                ps.setString(2, upwd);
                ps.executeUpdate();
                resp.sendRedirect("userLogin.jsp");
            }
            ps.close();
            rs.close();
            con.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
